﻿using UnityEngine;
using System.Collections;

public class SmoothBar : MonoBehaviour
{
    public UILabel numberLabel;
    public UISprite topSprite;
    public UISprite smoothSprite;
    //public BiasSlider biasSlider;
    private float currentSmoothValue;
    private double currentValue;
    private double maxValue;

    public GameObject runnerEffect;

    public void Init(double currentValue, double maxValue)
    {
        this.currentValue = currentValue;
        this.maxValue = maxValue;
        if(maxValue != 0)
        {
            currentSmoothValue = (float)currentValue / (float)maxValue;
        }
        else
        {
            currentSmoothValue = 0;
        }
        topSprite.fillAmount = currentSmoothValue;
        if(smoothSprite != null)
        {
            smoothSprite.fillAmount = currentSmoothValue;
        }
        if (numberLabel != null)
        {
            numberLabel.text = currentValue.ToString() + "/" + maxValue;
        }
    }

    public void SetValue(double currentValue, double maxValue)
    {
        this.currentValue = currentValue;
        this.maxValue = maxValue;
        float v = 0;
        if (maxValue != 0)
        {
            v = (float)currentValue / (float)maxValue;
        }
        //if(topSprite != null)
        //{
            topSprite.fillAmount = v;
        //}
        //else
        //{
        //    biasSlider.SetValue(v);
        //}
        if (numberLabel != null)
        {
            numberLabel.text = currentValue.ToString() + "/" + maxValue;
        }

    }
    public void SetValue(double currentValue)
    {
        SetValue(currentValue, maxValue);
    }
    private float smoothSpeed = 0.5f;
    private float delayTimer = 0f;
    private float delayTime = 0.5f;
    public void Update()
    {
        float v = 0;
        if(maxValue != 0)
        {
            v = (float)(currentValue / maxValue);
        }
        if(currentSmoothValue != v)
        {
            if(currentSmoothValue < v)
            {
                currentSmoothValue = v;
            }
            else
            {
                currentSmoothValue = Mathf.Max(currentSmoothValue -
                    Time.deltaTime * smoothSpeed,v);
            }
            if (smoothSprite != null)
            {
                smoothSprite.fillAmount = currentSmoothValue;
            }
            if(runnerEffect != null)
            {
                runnerEffect.SetActive(true);
                float x = smoothSprite.width * currentSmoothValue;
                runnerEffect.transform.localPosition = new Vector3(x,0,0);
                delayTimer = delayTime;
            }
        }
        else
        {
            if (runnerEffect != null)
            {
                delayTimer -= Time.deltaTime;
                if(delayTimer <= 0)
                {
                    runnerEffect.SetActive(false);
                }
            }
        }
    }
}
